<?php
namespace app\api\controller;

use app\common\controller\Common;
use think\Db;
use app\api\controller\SensitiveCategory;
use app\api\controller\SensitiveWord;
use app\api\controller\FileHandle;

class Sensitive{
    protected static $Request;

    function __construct() {
        self::$Request = request()->param();
    }

    public function index()
    {
        $id = self::$Request['id'];
        $whereCondt = [];

        if ($id>0) {
            $whereCondt['id'] = $id;
        }
        
        $res = self::selectSensitiveLogic($whereCondt);
        return resultArray(['data' => $res->data]);
    }

    public function upload()
    {
        try {
            //文件上传
            $file = request()->file('file');
            if (!$file) {
                return resultArray(['error' => '文件上传失败']);
            }
            //移动文件
            $info = $file->validate(['ext' => ['xls', 'xlsx']])->move(config('huisheng.SENSITIVE_PATH'));
            if (!$info) {
                return resultArray(['error' => '文件处理失败']);
            }
            // 获取参数
            $model = Model('Sensitive');
            $param = input('param.');
            $cid = $param['cid']; // 分类ID
            $path = $info->getSaveName();
            $suffix = $info->getExtension(); // 文件后缀
            $title = $param['title'];
            $describe = $param['describe'];

            $res = self::validateSensitiveIsExist($cid);
            if (!$res->isSuccess) {
                // 文件不存在 | 创建 | 获取文件ID
                $res = self::createSensitiveLogic($cid, $path, $title, $describe);
                if (!$res->isSuccess) {
                    return resultArray(['error' => lang('upload_failed')]);
                }
                $sid = $res->data->id; // 文件ID
                $returnInfo = lang('upload_successful');
            }else {
                // 文件存在 | 获取文件ID
                $sid = $res->data->id;
                $returnInfo = lang('merge_successful');

                // 更新名称、描述
                $whereCondt = [
                    'id' => $sid,
                ];
                $updateData = [
                    'title' => $title,
                    'describe' => $describe,
                    'status' => 0
                ];
                self::updateSensitiveCore($whereCondt, $updateData);
            }

            // 读取文件内容 | 插入词汇
            $filePath = config('huisheng.SENSITIVE_PATH').$path;
            // $sensitiveArr = cusReadFile($filePath, 1); // 敏感词数组
            $res = FileHandle::readExcel($filePath, $suffix, 0);
            if (!$res->isSuccess) { return $res; }
            $sensitiveArr = $res->data->res;

            // 批量添加敏感词
            $res = SensitiveWord::batchCreateSensitiveWordLogic($sid, $sensitiveArr);
            if ($res->isSuccess) {
                return resultArray(['data' => $returnInfo]);
            }else {
                return resultArray(['error' => $res->info]);
            }
        } catch (\Exception $e) {
            return resultArray(['error' => $e->getMessage()]);
        }
    }

    /**
     * 删除敏感词文件 - Api
     */
    public function deleteSensitive() {
        try {
            $id = self::$Request['id'];
            $res = self::deleteSensitiveLogic($id);
            return JRes($res);
        } catch (Exception $e) {
            return resultArray(['error' => $e->getMessage()]);
        }
    }

    /**
     * 删除敏感词文件 - Api
     */
    public function batchDeleteSensitive() {
        try {
            $idArr = json_decode(self::$Request['id_arr'], true);
            $res = self::batchDeleteSensitiveLogic($idArr);
            return JRes($res);
        } catch (Exception $e) {
            return resultArray(['error' => $e->getMessage()]);
        }
    }

    /**
     * 下载敏感词文件 - Api
     */
    public function downloadSensitive() {
        try {
            $id = self::$Request['id'];
            $res = self::downloadSensitiveLogic($id);
            return resultArray(['data' => $res->data]);
        } catch (Exception $e) {
            return resultArray(['error' => $e->getMessage()]);
        }
    }

    /**
     * 下载敏感词文件模板 - Api
     */
    public function downloadSensitiveTemplate() {
        try {
            $res = self::downloadSensitiveTemplateLogic();
            return resultArray(['data' => $res->data]);
        } catch (Exception $e) {
            return resultArray(['error' => $e->getMessage()]);
        }
    }

    /**
     * 更新敏感词树 - Api
     */
    public function updateSensitiveTree() {
        try {
            $id = self::$Request['id'];
            $res = self::updateSensitiveTreeLogic($id);
            return JRes($res);
        } catch (Exception $e) {
            return resultArray(['error' => $e->getMessage()]);
        }
    }

    /**
     * 检测敏感词服务是否可用
     */
    public static function verifySensitiveServiceIsEnable() {
        $param = [
            'id' => '0',
            'texts' => ''
        ];
        $res = json_decode(curl_post(config('huisheng.SENSITIVE_URL'), json_encode($param)), true);
        if ($res['status']=='200') {
            return operationRes(true, 'Service Enable');
        }
        return operationRes(false, 'Service Disable');
    }


    // 批量删除敏感词文件
    public static function batchDeleteSensitiveLogic($idArr) {
        $res = self::verifySensitiveServiceIsEnable();
        if (!$res->isSuccess) { return $res; }
        
        // 批量删除敏感词文件
        self::batchDeleteSensitiveCore($idArr);

        // 批量删除敏感词
        Model('SensitiveWord')::where(['sid' => ['in', $idArr]])->delete();

        // 更新敏感词树
        $res = self::updateSensitiveTreeLogic();

        return operationRes(true, lang('delete_successful'));
    }

    // 更新敏感词树 - Logic
    public static function updateSensitiveTreeLogic($id=0) {
        $res = self::verifySensitiveServiceIsEnable();
        if (!$res->isSuccess) { return $res; }

        if ($id!='0') {
            // 当前需要更新的文件，状态改为更新中
            $whereCondt = ['id' => $id];
            $updateData = ['status' => 2];
            $res = self::updateSensitiveLogic($whereCondt, $updateData);
            if (!$res->isSuccess) { return $res; }
        }

        // 其他生效中的文件，状态改为更新中
        $whereCondt = ['status' => 1];
        $updateData = ['status' => 2];
        $res = self::updateSensitiveLogic($whereCondt, $updateData);

        // 查询出更新中的文件下的词，并组成@分割格式
        $res = SensitiveWord::selectWordsByUpdatingSensitiveLogic();
        $list = $res->data->list;
        $str = '';
        if (!empty($list)) {
            foreach ($list as $key => $val) {
                $val['name'] = trim($val['name']);
                if ($key=='0') {
                    $str .= $val['name'];
                }else {
                    $str .= '@'.$val['name'];
                }
            }
        }

        if ($str!='') {
            // 有敏感词
            // 切换词库
            self::changeSensitiveDataset($id, 1);

            // 请求更新词树的接口
            $res = self::sendUpdateSensitiveTree($id, $str);
            $code = $res->data->status;
        }else {
            // 无敏感词
            // 切换词库
            $res = self::changeSensitiveDataset($id, 0);
            $code = $res->data->status;
        }

        // 请求完成，将更新中的状态，变为更新完成
        $whereCondt = ['status' => 2];
        $updateData = ['status' => 1];
        $res = self::updateSensitiveLogic($whereCondt, $updateData);

        // 返回
        if ($code=='200') {
            return operationRes(true, lang('update_successful'), ['list' => $list]);
        }else {
            return operationRes(false, lang('update_failed'));
        }
    }

    // 更新敏感词树请求
    public static function sendUpdateSensitiveTree($id, $texts) {
        $param = [
            'id' => (string)$id,
            'texts' => (string)$texts
        ];
        $res = json_decode(curl_post(config('huisheng.SENSITIVE_UPDATE'), json_encode($param)), true);
        $code = $res['status'];
        if ($code=='200') {
            $info = lang('update_successful');
            return operationRes(true, $info, $res);
        }else {
            $info = lang('update_failed');
            return operationRes(false, $info);
        }
    }

    /**
     * 切换敏感词词库请求
     * @param $flag 0-默认，1-用户敏感词
     */
    public static function changeSensitiveDataset($id, $flag) {
        $param = [
            'id' => (string)$id,
            'flag' => (string)$flag
        ];
        $res = json_decode(curl_post(config('huisheng.SENSITIVE_CHANGE'), json_encode($param)), true);
        return operationRes(true, 'Execute Finished', $res);
    }

    // 下载敏感词文件模板 - Logic
    public static function downloadSensitiveTemplateLogic() {
        // 生成文件，并获取文件地址
        $obj = [
            'list' => [
                ['name' => '敏感词1'],
                ['name' => '敏感词2'],
                ['name' => '敏感词3']
            ],
            'fileFolder' => config('huisheng.SENSITIVE_DOWNLOAD'),
            'fileName' => '敏感词模板'
        ];
        $res = FileHandle::exportExcel($obj, 0);
        if (!$res->isSuccess) { return $res; }
        $path = $res->data->res;

        // 返回
        return operationRes(true, lang('operation_successful'), ['path' => $path]);
    }

    // 下载敏感词文件 - Logic
    public static function downloadSensitiveLogic($id) {
        // 获取敏感词文件
        $whereCondt = [
            'id' => $id
        ];
        $res = self::selectSensitiveLogic($whereCondt);
        if (empty($res->data->list)) {
            return operationRes(false, lang('operation_failed'));
        }
        $sensitive = $res->data->list[0];

        // 生成文件，并获取文件地址
        $obj = [
            'list' => $sensitive['words'],
            'fileFolder' => config('huisheng.SENSITIVE_DOWNLOAD'),
            'fileName' => $sensitive['title'].'-'.$sensitive['category']['name']
        ];
        $res = FileHandle::exportExcel($obj, 0);
        if (!$res->isSuccess) { return $res; }
        $path = $res->data->res;

        // 返回
        return operationRes(true, lang('operation_successful'), ['path' => $path]);
    }

    // 验证该分类下是否存在文件
    public static function validateSensitiveIsExist($cid) {
        $whereCondt = [
            'cid' => $cid
        ];
        $res = self::selectSensitiveLogic($whereCondt);
        if (!empty($res->data->list)) {
            return operationRes(true, lang('exist'), $res->data->list[0]);
        }else {
            return operationRes(false, lang('not_exist'));
        }
    }

    // 查询Sensitive - Logic
    public static function selectSensitiveLogic($whereCondt) {
        return self::selectSensitiveCore($whereCondt);
    }

    // 创建Sensitive - Logic
    public static function createSensitiveLogic($cid, $path, $title, $describe) {
        $uid = 0;
        return self::createSensitiveCore($uid, $cid, $path, $title, $describe);
    }

    // 更新Sensitive - Logic
    public static function updateSensitiveLogic($whereCondt, $updateData) {
        return self::updateSensitiveCore($whereCondt, $updateData);
    }

    // 更新Sensitive的修改时间 - Logic
    public static function updateSensitiveUpdateTimeLogic($id) {
        $whereCondt = ['id' => $id];
        $updateData = ['update_time' => time()];
        return self::updateSensitiveCore($whereCondt, $updateData);
    }

    // 删除Sensitive - Logic
    public static function deleteSensitiveLogic($id) {
        $res = self::verifySensitiveServiceIsEnable();
        if (!$res->isSuccess) { return $res; }

        // 删除Sensitive文件
        $whereCondt = [
            'id' => $id
        ];
        $res = self::deleteSensitiveCore($whereCondt);

        // 删除对应敏感词
        $whereCondt = [
            'sid' => $id
        ];
        $res = SensitiveWord::deleteSensitiveWordLogic($whereCondt);

        // 更新敏感词树
        $res = self::updateSensitiveTreeLogic();
        return $res;
    }

    // 删除Sensitive - Core
    private static function deleteSensitiveCore($whereCondt) {
        $res = Model('Sensitive')::where($whereCondt)->delete();
        if ($res) {
            return operationRes(true, lang('delete_successful'));
        }else {
            return operationRes(false, lang('delete_failed'));
        }
    }

    // 批量删除Sensitive - Core
    private static function batchDeleteSensitiveCore($idArr) {
        // 批量删除敏感词文件
        Model('Sensitive')::destroy($idArr);

        return operationRes(true, lang('delete_successful'));
    }

    // 更新Sensitive - Core
    private static function updateSensitiveCore($whereCondt, $updateData) {
        $res = Model('Sensitive')::where($whereCondt)->update($updateData);
        if ($res) {
            return operationRes(true, lang('update_successful'));
        }else {
            return operationRes(true, lang('update_failed'));
        }
    }

    // 查询Sensitive - Core
    private static function selectSensitiveCore($whereCondt) {
        $source = Model('Sensitive')::with([
            'category',
            'words' => function($query) {
                $query->field(['id', 'sid','name']);
            }
        ]);
        $list = $source->where($whereCondt)->order('id desc')->select();

        // 返回结果
        $returnData = [
            'list' => $list
        ];
        return operationRes(true, lang('query_successful'), $returnData);
    }

    // 创建Sensitive - Core
    private static function createSensitiveCore($uid, $cid, $path, $title, $describe) {
        $timestamp = time();
        $createData = [
            'uid' => $uid,
            'cid' => $cid,
            'path' => $path,
            'title' => $title,
            'describe' => $describe,
            'status' => 0,
            'create_time' => $timestamp,
            'update_time' => $timestamp
        ];
        if ($res = Model('Sensitive')::create($createData)) {
            return operationRes(true, lang('add_successful'), $res);
        }else {
            return operationRes(false, lang('add_failed'));
        }
    }

    public function update($id)
    {
        $model = Model('Sensitive')->get($id);
        if(is_file(config('huisheng.SENSITIVE_PATH') . $model->path)){
            $strs = '';
            foreach(file(config('huisheng.SENSITIVE_PATH') . $model->path) as $str){
                $strs .= $str."@";
            }
            $strs = substr($strs,0,-1);
            $param = [
                'id' => (string)$id,
                'texts' => (string)$strs
            ];
            $result = json_decode(curl_post(config('huisheng.SENSITIVE_UPDATE'), json_encode($param)), 1);
            if (!isset($result['status'])) {
                return resultArray(['error' => '请求敏感词接口失败']);
            } else if ($result['status'] != 200) {
                return resultArray(['error' => $result['description']]);
            }
            $model->status = 1;
            $model->save();
            return resultArray(['data' => '']);           
        }else{
            return resultArray(['error' => '未找到文件']);
        }
    }

    public function download($id)
    {
        $model = Model('Sensitive')->get($id);
        $url = config('huisheng.SENSITIVE_PATH') . $model->path;
        if(is_file($url)){
            download_result_one($url, "敏感词列表");
        }
        return resultArray(['error' => '文件不存在']);
    }
}
